`

Device type: general purpose

Running: Linux 4.X|5.X

OS CPE: cpe:/o:linux:linux_kernel:4 cpe:/o:linux:linux_kernel:5

OS details: Linux 4.15 - 5.6

Network Distance: 1 hop

Lets create a bash script that can parse this output and sort it by

IP address and operating system (Listing 4-16).

#!/bin/bash

HOSTS="$*"

1 if [[ "${EUID}" -ne 0 ]]; then

echo "The Nmap OS detection scan type (-O) requires root privileges."

exit 1

fi

2 if [[ "$#" -eq 0 ]]; then

echo "You must pass an IP or an IP range"

exit 1

fi

echo "Running an OS Detection Scan against ${HOSTS}..."

3 nmap_scan=$(sudo nmap -O ${HOSTS} -oG -)

4 while read -r line; do

ip=$(echo "${line}" | awk '{print $2}')

os=$(echo "${line}" | grep OS | awk -F'OS: ' '{print $2}' | sed 's/Seq.*//g')

5 if [[ -n "${ip}" ]] && [[ -n "${os}" ]]; then

echo "IP: ${ip} OS: ${os}"

fi

done <<< "${nmap_scan}"

Listing 4-16

Parsing an operating system detection scan

Because this scan requires root privileges, we check for the

effective user’s ID 1. If the user ID isnt equal to zero, we exit

because there is no point in continuing if the user isnt using root

privileges. We then check whether the user passed target hosts as

arguments on the command line 2. At 3, we run the Nmap operating

system detection scan against these targets, which we’ve assigned to

the HOSTS variable.

We use a while loop to iterate through the scan results, parsing

each line and assigning the IP address in the output to the ip

variable. We then parse the line a second time to extract the

operating system information from Nmap. We clean the output using

sed so it shows only the operating system, removing everything

after the word Seq. Next, we check whether both the ip and os

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks